package sample.clients;



import org.hibernate.HibernateException;
import org.hibernate.Query;

import sample.dao.DAO;
import sample.entity.Advert;
import sample.entity.Category;
import sample.entity.User;

public class PostAdvert  extends DAO{

	public static void main(String[] args) throws Exception {
		System.out.println("Posting Advert");
		
		PostAdvert self=new PostAdvert();
		
		Advert advert=self.create("Andrew", "Electro", "Gitara", "100 dolariv");
		
	
		
	}
	
	
	
	public Advert create(String username,String categoryTitle,
						  String title,String message) throws Exception{
		try{
			begin();
			Query userQuery=getSession().createQuery("from User where name = :username");
			userQuery.setString("username", username);
			User user=(User)userQuery.uniqueResult();
			
			Query categoryQuery=getSession().createQuery("from Category where title = :categoryTitle");
			categoryQuery.setString("categoryTitle", categoryTitle);
			Category category=(Category)categoryQuery.uniqueResult();
			
			//create and save new advert
			Advert advert=new Advert();
			advert.setTitle(title);
			advert.setMessage(message);
			advert.setUser(user);
			
			getSession().save(advert);
			
			category.getAdverts().add(advert);
			
			getSession().save(category);
			
			commit();
			return advert;
			
		}
		catch(HibernateException e){
			throw new Exception(e.getMessage());
		}
		finally{
			close();
		}
	}
}
